
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText


# 一些配置
_email_server = "mail.cjsc.com.cn"
_email_account = "kuangcb@cjsc.com"
_email_pwd = "242833@cjsc"
_email_recv_blog_list = [
  "zhangqing1@cjsc.com",
  "lihui4@cjsc.com",
  "kuangcb@cjsc.com"
]

_email_recv_err_list = [
  "kuangcb@cjsc.com"
]

# 报警消息模板
_msg_fmt = [
  "报警条件：排名大于第 8 名 或者有新的账号，设备加入",
  "",
  "博睿测速异常情形汇总",
  "",
  "得分排名情况：",
  "上海：排名 %(rank_sh)d, 得分 %(score_sh)d",
  "深圳：排名 %(rank_sz)d, 得分 %(score_sz)d",
  "北京：排名 %(rank_bj)d, 得分 %(score_bj)d",
  "",
  "账号或者设备新增情形：",
  "新增账号：%(account_list_str)s",
  "新增设备：%(imsi_list_str)s"
]


# 日常报告模板
_report_fmt = [
  "博睿测速当日情况汇总",
  "",
  "排名情况（上海 - 排名%(rank_sh)d）",
  "",
  "%(str_sh)s",
  "",
  "排名情况（深圳 - 排名%(rank_sz)d）",
  "",
  "%(str_sz)s",
  "",
  "排名情况（北京 - 排名%(rank_bj)d）",
  "",
  "%(str_bj)s",
  "",
  "账号或者设备新增情形：",
  "新增账号：%(account_list_str)s",
  "新增设备：%(imsi_list_str)s"
]



def _format_report_email_msg(data):

  msg = MIMEMultipart('mixed')
  msg["Subject"] = "博睿测速当日情况汇总"
  msg["From"] = _email_account
  msg["To"]= ";".join(_email_recv_blog_list)

  str_tpl = "\t%(rank)s\t%(name)s\t%(score)s\r\n"
  str_sh = "\t排名\t券商\t分数\r\n"
  list_sh = data["list_sh"]
  for row in list_sh:
    str_sh = str_sh + str_tpl % row
  data["str_sh"] = str_sh

  str_sz = "\t排名\t券商\t分数\r\n"
  list_sz = data["list_sz"]
  for row in list_sz:
    str_sz = str_sz + str_tpl % row
  data["str_sz"] = str_sz

  str_bj = "\t排名\t券商\t分数\r\n"
  list_bj = data["list_bj"]
  for row in list_bj:
    str_bj = str_bj + str_tpl % row
  data["str_bj"] = str_bj

  text = "\r\n".join(_report_fmt) % data
  text_plain = MIMEText(text, "plain", "utf-8")
  msg.attach(text_plain)
  return msg


def _format_spy_email_msg(data):

  msg = MIMEMultipart('mixed')
  msg["Subject"] = "博睿测速异常提醒"
  msg["From"] = _email_account
  msg["To"]= ";".join(_email_recv_err_list)
  text = "\r\n".join(_msg_fmt) % data
  text_plain = MIMEText(text, "plain", "utf-8")
  msg.attach(text_plain)
  return msg



def send_email(is_report_data, obj_data):

  if(is_report_data):
    msg = _format_report_email_msg(obj_data)
  else:
    msg = _format_spy_email_msg(obj_data)

  smtp = smtplib.SMTP()
  smtp.connect(_email_server)
  smtp.login(_email_account, _email_pwd)
  smtp.sendmail(_email_account, _email_recv_blog_list, msg.as_string())
  smtp.quit()
  print("mail sended")

if __name__ == "__main__":

  send_email("hello world")
  print(".done")